package yambal.net.googledata
{
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	
	import yambal.net.googledata.service.IService;
	
	public class Accounts
	{
		public function Accounts()
		{
		}

		public function ClientLogin(google_user:GoogleUser, service:IService, compulsion:Boolean = false):void{
			trace("Accounts.ClientLogin:" + google_user.email + "/" + service.service_name);
			
			var authed:Auth = google_user.getAuth(service);
			
			if(authed == null || compulsion){
				// パラメタ
				var params:URLVariables = new URLVariables();
				params.Email = google_user.email;
				params.Passwd = google_user.password;
				params.service = service.service_name;
				if(google_user.isApps){
					params.accountType = "HOSTED";
				}
				
				var loader:AuthLoader = new AuthLoader();
				loader.google_user = google_user;
				loader.service = service;
				
				var req:URLRequest = new URLRequest();
				req.url = "https://www.google.com/accounts/ClientLogin";
				req.method = "get";
				req.data = params;
				
				loader.addEventListener(Event.COMPLETE, this.onClientLogin);
				loader.load(req);
				
			}else{
				// すでに認証すみ
				
			}
		}
		
		private function onClientLogin(event:Event):void{
			var loader:AuthLoader = event.currentTarget as AuthLoader
			loader.removeEventListener(Event.COMPLETE, this.onClientLogin);
			
			var auth:Auth = new Auth();
			auth.service_name = loader.service.service_name;
			
			var response_split:Array = String(loader.data).split('\n');
			for(var i:int = 0; i<response_split.length; i++){
				var aug_split:Array = String(response_split[i]).split("=");
				if(aug_split.length>1){
					var aug_name:String = String(aug_split[0]).toLowerCase();
					var aug_value:String = String(aug_split[1]);
					switch (aug_name){
						case "sid":
							auth.sid = aug_value;
							break;
						case "lsid":
							auth.lsid = aug_value;
							break;
						case "auth":
							auth.auth = aug_value;
							break;
						default:
							break;
					}
				}
			}
			
			loader.google_user.addAuth(auth);
			
			trace("authed");
		}
	}
}